using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Forge.OpenAI;
using ChatGPT.Net;
using Forge.OpenAI.Models.ChatCompletions;
using ChatGPT.Net.DTO.ChatGPT;
using System.Net;

namespace ChatGpt_WebApp.ThirdApi
{
    public class OfficialChatGptApi : ChatApiBase
    {
        // ChatGPT Official API
        readonly ChatGpt bot;
        public OfficialChatGptApi(ILogger<OfficialChatGptApi> logger, ApiConfig config) : base(logger, config)
        {
            bot = new ChatGpt(apiContext.ApiKey, new ChatGPT.Net.DTO.ChatGPT.ChatGptOptions()
            {
                MaxTokens = gptConfig.MaxTokenLength,
            });

            //如果是 pk- 开头则使用Pawan的服务器
            if (apiContext.ApiKey.StartsWith("pk-"))
            {
                bot.Config.BaseUrl = "https://api.pawan.krd";
            }
            //否则使用海外代理
            else
            {
                bot.Config.BaseUrl = gptConfig.OverseasProxy;
            }
        }

        public override async Task<ChatResult> Ask(string question, string conversationId)
        {
            var result = new ChatResult();
            try
            {
                var count = 1;
                do
                {
                    result.Content = await bot!.Ask(question, conversationId);
                    //循环等待回答
                    if (string.IsNullOrWhiteSpace(result.Content)) await Task.Delay(1000);
                } while (string.IsNullOrWhiteSpace(result.Content) && ++count < 5);

                if (string.IsNullOrWhiteSpace(result.Content))
                {
                    logger.LogWarning("回答为空" + question.Length);
                    result.Status = ChatResultStatus.TimeOut;
                    result.Success = false;
                    result.Content = "源服务器问答请求有些繁忙，待会儿再试试吧";
                    return result;
                }
            }
            catch (System.Net.Http.HttpRequestException e)
            {
                logger.LogError(e, "请求异常，问题:" + question);
                result.Exception = e;
                result.Success = false;
                if (e.StatusCode == HttpStatusCode.BadRequest)
                {
                    result.Content = $"问题被源服务器拒绝回答了,可能是因为问题过长或者是问题中包含了敏感词汇，请在右上角清理会话后再试试吧!";
                }
                else if (e.StatusCode == HttpStatusCode.TooManyRequests)
                {
                    result.Content = "提问太过频繁了，请稍后再试试吧!";
                }
                else
                {
                    result.Content = "源服务器响应出现异常";
                }
                result.Content+=  $"\n会话ID:{conversationId}"+$"\n错误信息:{e.Message}";
                
                return result;
            }
            catch (Exception e)
            {
                logger.LogError(e, "提问时出现错误,问题长度" + question.Length);
                result.Exception = e;
                result.Success = false;
                result.Content = "我这边好像出现了一些异常状况";
                return result;
            }

            result.Success = true;
            result.Status = ChatResultStatus.Success;

            return result;
        }

        public async override Task<string> AskStream(Action<string> callback, string prompt, string? conversationId = null)
        {
            try
            {
                return await bot!.AskStream(callback, prompt, conversationId);
            }
            catch (System.Exception ex)
            {
                var msg = ex.Message;
                callback(msg);
                return msg;
            }
        }

        public override Task ResetConversation(string conversationId)
        {
            bot.RemoveConversation(conversationId);
            return Task.CompletedTask;
        }

        /// <summary>
        /// 设置机器人配置
        /// </summary>
        /// <param name="action"></param>
        public void BotSetting(Action<ChatGptOptions> action)
        {
            action(bot.Config);
        }
    }
}